﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Business
{
    public partial class frm_Edit_ExportQuotation : Form
    {
        private INISettings mySetting;
        private SqlConnection myConnection;

        public string quotation_id;

        private string prefix;
        private string yearmonth;
        private string indexnumber;
        private string suffix;
        private string versionnumber;

        public frm_Edit_ExportQuotation()
        {            
            InitializeComponent();
            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            this.quotation_id = null;
            this.prefix = null;
            this.yearmonth = null;
            this.indexnumber = null;
            this.versionnumber = null;
            this.suffix = null;
            LoadCustomer();
            this.customerID.Properties.AutoComplete = true;
            LoadStaff();
            this.requestedBy.Properties.AutoComplete = true;
            this.madeBy.Properties.AutoComplete = true;
            LoadBankAccount();
            this.bankAccount.Properties.AutoComplete = true;
        }

        ///////////////////////////////////////////////////////////
        /// Load Data
        ///////////////////////////////////////////////////////////
        public bool LoadData()
        {
            bool ret = true;

            if (string.IsNullOrEmpty(quotation_id))
            {
                ret = false;
            }
            else
            {
                try
                {
                    myConnection.Open();
                    SqlCommand sql_cmd = myConnection.CreateCommand();
                    sql_cmd.CommandText = "SELECT * FROM [241_ExportQuotation] WHERE QuotationID='" + quotation_id + "'";
                    SqlDataReader dataReader = sql_cmd.ExecuteReader();
                    if (dataReader.Read())
                    {
                        this.prefix = quotation_id.Substring(0, 3);
                        this.yearmonth = quotation_id.Substring(4, 4);
                        this.indexnumber = quotation_id.Substring(9, 3);
                        this.versionnumber = quotation_id.Substring(13, 1);

                        if (quotation_id.Length >= 17)
                        {
                            this.suffix = quotation_id.Substring(15, 2);
                        }

                        this.quotationID.Text = prefix + "-" + yearmonth + "-" + indexnumber + "-" + versionnumber;
                        this.suffixID.Text = suffix;

                        for (int i = 0; i < this.requestedBy.Properties.Items.Count; i++)
                        {
                            ComboboxItem request = (ComboboxItem)this.requestedBy.Properties.Items[i];
                            if (request.Value.ToString().Trim() == dataReader["RequestedBy"].ToString().Trim())
                            {
                                this.requestedBy.SelectedIndex = i;
                            }
                        }

                        for (int i = 0; i < this.madeBy.Properties.Items.Count; i++)
                        {
                            ComboboxItem made = (ComboboxItem)this.madeBy.Properties.Items[i];
                            if (made.Value.ToString().Trim() == dataReader["MadeBy"].ToString().Trim())
                            {
                                this.madeBy.SelectedIndex = i;
                            }
                        }

                        this.inputDate.EditValue = DateTime.Parse(dataReader["InputDate"].ToString().Trim());

                        for (int i = 0; i < this.customerID.Properties.Items.Count; i++)
                        {
                            ComboboxItem customer = (ComboboxItem)this.customerID.Properties.Items[i];
                            if (customer.Value.ToString().Trim() == dataReader["CustomerID"].ToString().Trim())
                            {
                                this.customerID.SelectedIndex = i;
                            }
                        }

                        for (int i = 0; i < this.bankAccount.Properties.Items.Count; i++)
                        {
                            ComboboxItem bank = (ComboboxItem)this.bankAccount.Properties.Items[i];
                            if (bank.Value.ToString().Trim() == dataReader["BankInfor"].ToString().Trim())
                            {
                                this.bankAccount.SelectedIndex = i;
                            }
                        }

                        this.noteValue.Text = dataReader["Note"].ToString().Trim();
                        this.expiredDate.EditValue = DateTime.Parse(dataReader["ExpiredDate"].ToString().Trim());

                        if ((bool)dataReader["ComOrPart"])
                        {
                            this.compQuotation.Checked = true;
                        }
                        else
                        {
                            this.compQuotation.Checked = false;
                        }
                    }
                    dataReader.Close();
                    sql_cmd.Dispose();
                    myConnection.Close();
                }
                catch
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    ret = false;
                }
            }

            return ret;
        }        

        ///////////////////////////////////////////////////////////
        /// Get Customer List
        ///////////////////////////////////////////////////////////
        private void LoadCustomer()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT CustomerID, FullName FROM [222_Customer] ORDER BY FullName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["FullName"].ToString();
                    item.Value = dataReader["CustomerID"].ToString();
                    this.customerID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get Customer list");
            }
        }

        ///////////////////////////////////////////////////////////
        /// Get Staff List
        ///////////////////////////////////////////////////////////
        private void LoadStaff()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT StaffID, StaffName FROM [222_Staff] ORDER BY StaffName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["StaffName"].ToString().Trim() + "(" + dataReader["StaffID"].ToString().Trim() + ")";
                    item.Value = dataReader["StaffID"].ToString().Trim();
                    this.requestedBy.Properties.Items.Add(item);
                    this.madeBy.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get Staff list");
            }
        }

        ///////////////////////////////////////////////////////////
        /// Get Bank Account List
        ///////////////////////////////////////////////////////////
        private void LoadBankAccount()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT BankAccountID FROM [222_BankAccount] ORDER BY BankAccountID";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["BankAccountID"].ToString();
                    item.Value = dataReader["BankAccountID"].ToString();
                    this.bankAccount.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get Bank Account list");
            }
        }

        /////////////////////////////////////
        /// Check new quotation ID conflict
        /////////////////////////////////////
        private bool checkConlict(string id)
        {
            bool ret = false;
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT QuotationID FROM [241_ExportQuotation] WHERE QuotationID='" + id + "'";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    ret = true;
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot check conflict for new quotation ID");
            }
            return ret;
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        ///////////////////////////////////////
        /// Add new export quotation
        ///////////////////////////////////////
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            ComboboxItem item;
            string customer = null, requested = null, made = null, bankinfo = null;            
            bool pass = true;            
            string error = null;

            string new_id = null;

            this.versionnumber = (Int32.Parse(this.versionnumber) + 1).ToString();

            new_id = this.prefix + "-" + this.yearmonth + "-" + this.indexnumber + "-" + this.versionnumber;

            if (!string.IsNullOrEmpty(this.suffix))
            {
                new_id += "-" + this.suffix;
            }
            
            if (pass)
            {
                if (checkConlict(new_id))
                {
                    pass = false;
                    error = "The Quotation ID is existed. Please try again";                    
                }
            }

            if (pass)
            {
                if (this.requestedBy.SelectedIndex >= 0)
                {
                    item = (ComboboxItem)requestedBy.SelectedItem;
                    requested = item.Value.ToString();
                }

                if (this.madeBy.SelectedIndex >= 0)
                {
                    item = (ComboboxItem)madeBy.SelectedItem;
                    made = item.Value.ToString();
                }
            }

            /// Check Input date
            if (pass)
            {
                if (string.IsNullOrEmpty(inputDate.Text))
                {
                    pass = false;
                    error = "Please select Input Date";
                }
            }

            // Check customer 
            if (pass)
            {
                if (this.customerID.SelectedIndex >= 0)
                {
                    item = (ComboboxItem)this.customerID.SelectedItem;
                    customer = item.Value.ToString();
                }
                else
                {
                    pass = false;
                    error = "No Customer";
                }
            }

            /// Check Bank Info
            if (pass)
            {
                if (this.bankAccount.SelectedIndex < 0)
                {
                    pass = false;
                    error = "Please select Bank Account";
                }
                else
                {
                    item = (ComboboxItem)bankAccount.SelectedItem;
                    bankinfo = item.Value.ToString();
                }
            }

            /// Check Expired date
            if (pass)
            {
                if (string.IsNullOrEmpty(expiredDate.Text))
                {
                    pass = false;
                    error = "Please select Expired Date";
                }
            }

            if (pass)
            {
                /// Insert new Quotation
                DateTime inputdate;
                DateTime.TryParse(inputDate.DateTime.Date.ToString(), out inputdate);
                DateTime expireddate;
                DateTime.TryParse(expiredDate.DateTime.Date.ToString(), out expireddate);
                int comOrpart;
                if (compQuotation.Checked)
                {
                    comOrpart = 1;
                }
                else
                {
                    comOrpart = 0;
                }

                try
                {
                    myConnection.Open();
                    string sql = "INSERT INTO [241_ExportQuotation]"
                        + " (QuotationID, CustomerID, InputDate, RequestedBy, MadeBy, ComOrPart,"
                        + " ExpiredDate, BankInfor, Note)"
                        + " VALUES ('" + new_id + "', '" + customer + "', @inputdate, '" + requested + "',"
                        + " '" + made + "', " + comOrpart + ","
                        + " @expireddate, '" + bankinfo + "', '" + noteValue.Text + "')";
                    SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
                    cmd_sql.Parameters.Add("@inputdate", SqlDbType.DateTime).Value = inputdate.Date;
                    cmd_sql.Parameters.Add("@expireddate", SqlDbType.DateTime).Value = expireddate.Date;
                    cmd_sql.ExecuteNonQuery();
                    cmd_sql.Dispose();
                    myConnection.Close();
                    MessageBox.Show("Export Quotation added success.");
                    clearForm();
                }
                catch (Exception ex)
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    //MessageBox.Show("Cannot add Export Quotation. Please try again.");
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(error))
                {
                    MessageBox.Show(error);
                }
            }

        }

        private void clearForm()
        {
            foreach (Control c in this.Controls)
            {
                if (c is DevExpress.XtraEditors.TextEdit)
                {
                    ((DevExpress.XtraEditors.TextEdit)c).Text = null;
                }

                if (c is DevExpress.XtraEditors.ComboBoxEdit)
                {
                    ((DevExpress.XtraEditors.ComboBoxEdit)c).SelectedIndex = -1;
                }

                if (c is System.Windows.Forms.MaskedTextBox)
                {
                    ((System.Windows.Forms.MaskedTextBox)c).Text = null;
                }
            }
        }
    }
}
